package com.example.demo.controller;

import com.example.demo.enums.RedisPreEnum;
import com.example.demo.entity.ResponseInfo;
import com.example.demo.entity.User;
import com.example.demo.service.TokenService;
import com.example.demo.service.UserService;
import com.example.demo.common.PassToken;
import com.example.demo.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @创建人 Linzhou
 * @创建时间 2021/10/29
 * @描述
 **/
@RestController
@RequestMapping("/user")
@Api(value = "/user", tags = "用户接口")
public class UserController {

    @Resource
    UserService userService;

    @Resource
    TokenService tokenService;

    @Resource
    private RedisUtil redisUtil;

    @PostMapping("/save")
    @ApiOperation(value = "用户新增接口")
    public ResponseInfo<String> save(@RequestBody User user) {
        return ResponseInfo.successInfo(userService.save(user));
    }

    @PassToken
    @PostMapping("/login")
    @ApiOperation(value = "用户登录接口")
    public ResponseInfo<String> login(HttpServletRequest request, @RequestBody User user) {

        if (userService.login(user)) {
            user = userService.selectOne(user.getUserName());
            String token = tokenService.getToken(user);
            String key = RedisPreEnum.JWT_TOKEN_PRE.getPre() + user.getId();
            Long time = 7200L;
            if (redisUtil.hashKey(key)) {
                token = redisUtil.get(key).toString();
            } else {
                redisUtil.setT(key, token, time);
            }
            return ResponseInfo.successInfo(token);
        } else {
            return ResponseInfo.successInfo("账号密码错误");
        }
    }

    @GetMapping("/page")
    @ApiOperation(value = "用户分页接口")
    public ResponseInfo<String> page() {
        return ResponseInfo.successInfo("");
    }

}
